package com.hao.cdk.sm.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.collection.CollectionUtil;
import com.hao.cdk.sm.domain.entity.AccountUser;
import com.hao.cdk.sm.domain.dto.accountuser.*;
import com.hao.cdk.sm.domain.vo.accountuser.*;
import com.hao.cdk.sm.service.IAccountUserService;
import com.hao.cdk.sm.mapper.AccountUserMapper;
import org.springframework.stereotype.Service;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.apache.poi.ss.usermodel.Workbook;
import cn.hutool.core.date.DateUtil;
import java.util.Date;
import java.util.List;

/**
 * @author: 许自豪
 * @date: 2025-01-24 14:53:55
 * @description: 用户(AccountUser)表服务实现类
 */
@Service
public class AccountUserServiceImpl extends ServiceImpl<AccountUserMapper, AccountUser> implements IAccountUserService {
	
	/**
     * 分页查询
     *
     * @param dto dto
     * @return page
     */
    @Override
    public IPage<AccountUserPageVO> doPage(AccountUserPageDTO dto){
        return page(new Page<>(dto.getPageNum(), dto.getPageSize()), Wrappers.<AccountUser>lambdaQuery(BeanUtil.copyProperties(dto, AccountUser.class)))
        .convert(item -> BeanUtil.copyProperties(item, AccountUserPageVO.class));
    }

    /**
     * 列表查询
     *
     * @param dto dto
     * @return list
     */
    @Override
    public List<AccountUserListVO> doList(AccountUserListDTO dto){
        return BeanUtil.copyToList(list(Wrappers.<AccountUser>lambdaQuery(BeanUtil.copyProperties(dto, AccountUser.class))), AccountUserListVO.class);
    }
    
    /**
     * 获取单条数据
     *
     * @param id id
     * @return 单条数据
     */
    @Override
    public AccountUserGetVO doGetById(String id) {
        return BeanUtil.copyProperties(getById(id),AccountUserGetVO.class);
    }

    /**
     * 新增方法
     *
     * @param dto dto
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String doSave(AccountUserSaveDTO dto){
        AccountUser accountUser = BeanUtil.copyProperties(dto, AccountUser.class).setId(IdUtil.randomUUID());
        save(accountUser);
        return accountUser.getId();
    }
    
    /**
     * 修改方法
     *
     * @param dto dto
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean doUpdate(AccountUserUpdateDTO dto){
        return updateById(BeanUtil.copyProperties(dto, AccountUser.class));
    }
    
    /**
     * 删除数据
     *
     * @param ids id集合
     * @return 删除结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean doDelete(List<String> ids) {
        return removeByIds(ids);
    }
    
    /**
     * 导入
     *
     * @param file     文件
     * @param titleRow 文本头
     * @param headRow  解析头
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean importExcel(MultipartFile file, int titleRow, int headRow) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(headRow);
        params.setTitleRows(titleRow);
        InputStream inputStream = null;
        List<AccountUser> accountUsers;
        try {
            inputStream = file.getInputStream();
            accountUsers = BeanUtil.copyToList(ExcelImportUtil.importExcel(inputStream, AccountUserImportExcelDTO.class, params),
                    AccountUser.class);
        } catch (IOException e) {
            throw new RuntimeException("文件解析失败" + e.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
                
        for (AccountUser accountUser : accountUsers) {
            accountUser.setId(IdUtil.randomUUID());
        }
        return saveBatch(accountUsers);
    }

    /**
     * 根据ids导出
     *
     * @param ids ids
     */
    @Override
    public void exportExcel(List<String> ids, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams("用户", "用户", ExcelType.XSSF);
        List<AccountUserExportExcelVO> list = BeanUtil.copyToList(list(Wrappers.<AccountUser>lambdaQuery().in(CollectionUtil.isNotEmpty(ids)
            ,AccountUser::getId,ids)), AccountUserExportExcelVO.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, AccountUserExportExcelVO.class, list);
        // 将生成的 Excel 写入文件系统
        String fileName = "用户" + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";
        try {
            response.setHeader("content-disposition", "attachment:filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setHeader("file-name", URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
